import Axios from 'axios';
import Qs from 'qs';
import Store from '@/store';
import { baseURL } from '@/api/baseURL';

const server = Axios.create({
  method: 'post',
  baseURL,
  // 允许在向服务器发送前，修改post请求数据
  transformRequest: [data => Qs.stringify(data)],
  headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  params: {},
  // 负责 `params` 序列化的函数
  paramsSerializer: params => Qs.stringify(params),
  data: {},
  timeout: 150000,
  withCredentials: true,
});

// 不需要token的api
const whiteList = ['/v3/auth'];
// 不需要access_key的api
const accessKeyWhiteList = ['/v3/user/subaccount-by-key'];
// 需要access_key的api
const accessKeyList = ['/v3/user/subaccount-info', '/v3/user/subaccountaccess-del'];

server.interceptors.request.use(
  (config) => {
    if (whiteList.indexOf(config.url) === -1) {
      if (Store.getters.token) {
        Object.assign(config.data, { token: Store.getters.token });
        if (Store.getters.obAccessKey && accessKeyWhiteList.indexOf(config.url) === -1) {
          delete Object.assign(config.data, { access_key: Store.getters.obAccessKey }).puid;
          delete Object.assign(config.data).cuid;
        } else if (accessKeyList.indexOf(config.url) === -1) {
          delete Object.assign(config.data).access_key;
        }
        return config;
      }
      return Store.dispatch('Auth').then(() => {
        Object.assign(config.data, { token: Store.getters.token });
        if (Store.getters.obAccessKey && accessKeyWhiteList.indexOf(config.url) === -1) {
          delete Object.assign(config.data, { access_key: Store.getters.obAccessKey }).puid;
          delete Object.assign(config.data).cuid;
        } else if (accessKeyList.indexOf(config.url) === -1) {
          delete Object.assign(config.data).access_key;
        }
        return config;
      }).catch(() => {
        Store.commit('CLEAR_ALL');
        window.location.reload();
      });
    }
    return config;
  },
  error => Promise.reject(error),
);

server.interceptors.response.use(
  (response) => {
    // console.log(whiteList.indexOf(response.config.url.slice(baseURL.length)) === -1);
    if (response.data.status === -1) {
      // 没有登录
      Store.commit('SET_ID', undefined);
    } else if (response.data.status === -2 && whiteList.indexOf(response.config.url.slice(baseURL.length)) === -1) {
      // 没有token或token无效,且不在白名单
      Store.commit('CLEAR_ALL');
      window.location.reload();
    }
    return response;
  },
  error => Promise.reject(error),
);

export default server;
